from __future__ import division
import os
import subprocess


class WebServer:
  def do_popen(self, command_args):
    return repr(subprocess.Popen(command_args, stdout=subprocess.PIPE,).communicate()[0])
  # def do_popen(self, command_args):
  #   try:
  #     subprocess.Popen(command_args, 
  #   return repr(subprocess.Popen(command_args, stdout=subprocess.PIPE,).communicate()[0])

  def add_html(self, text, tag):
    return "<" + tag + ">" + text + \
      "</" + tag + ">"

if __name__ == "__main__":
  import getpass
  user = getpass.getuser()
  cwd = os.getcwd()
  
  w = WebServer()

  hostname = w.do_popen(["hostname"]).replace("\\n", "").replace("\'", "")

  print("<html>")
  print("<head>")
  print("%s" % w.add_html("Host: %s" % hostname, "title"))
  print("</head>")
  print("<body>")
  print("%s" % w.add_html("Welcome to %s" % hostname, "h2"))

  print(w.add_html("Controls", "h3"))

  print("<h4>Currently running processes for user %s:</h4>" % user)
  print(w.add_html(w.do_popen(["ps", "-u", "%s" % user]).strip("\'").replace("\\n", "<br />"), "p"))
  print("""<form action="kill_process.py" method="get">""")
  print("""Enter the PID for the process you would like to kill: <input type="text" name="pid" /><br />""")
  #print("""Enter the secret password: <input type="password" name="passwd" /><br />""")
  print("""<input type="submit" value="Kill process" />""")
  print("""</form>""")


  print("""<form action="reboot.py" method="get">""")
  print("""Enter the secret password to reboot: <input type="password" name="passwd" /><br />""")
  print("""<input type="submit" value="Reboot" />""")
  print("""</form>""")

  print(w.add_html("Host Information", "h3"))

  print(w.add_html(w.do_popen(["uptime"]).strip("\'").replace("\\n", ""), "p"))
  #proc = subprocess.Popen(['uptime'], stdout=subprocess.PIPE,)
  #s = str.split(repr(proc.communicate()[0]))
  #s = repr(proc.communicate()[0]).split("u")
  #print("%s" % w.add_html("Host has been up for " + s[3].replace(",", ""), "p"))
  #print(w.add_html(s[1], "p"))
  #for ss in s:
   # print("%s" % w.add_html(ss, "p"))

  print("<h4>Disk and Memory Usage</h4>")

  disk_space = w.do_popen(['df', '-h']).split("\\n")[1].split()
  print(w.add_html("Disk space used: %s<br />" % disk_space[2] + "Disk space free: %s" % disk_space[3], "p")) 

  memory = w.do_popen(["free", "-m"]).split("\\n")[1].split()
  print(w.add_html("Memory used: %sM<br />" % memory[2] + "Memory free: %sM" % memory[3], "p"))

  print("<h4>Network Statistics</h4>")
  print(w.add_html(w.do_popen(["netstat", "-s"]).strip("\'"), "p")).replace("\\n", "<br />")

  print("</body>")
  print("</html>")
